    package com.geokon.test.demo1.config;

    import java.io.IOException;
    import java.util.Collections;
    import java.util.HashSet;
    import java.util.Map;
    import java.util.Set;

    import org.eclipse.paho.mqttv5.client.MqttClient;
    import org.eclipse.paho.mqttv5.common.MqttException;
    import org.eclipse.paho.mqttv5.common.MqttMessage;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    import org.springframework.web.socket.TextMessage;
    import org.springframework.web.socket.WebSocketSession;
    import org.springframework.web.socket.handler.TextWebSocketHandler;

    import com.fasterxml.jackson.core.type.TypeReference;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.geokon.test.demo1.controller.TestController;

    @Component
    public class MyWebSocketHandler extends TextWebSocketHandler {
    private static final Logger log = LoggerFactory.getLogger(MyWebSocketHandler.class);
    private static final Set<WebSocketSession> sessions = Collections.synchronizedSet(new HashSet<>());

    @Autowired
    private TestController testController;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("websocket连接成功");
        sessions.add(session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, org.springframework.web.socket.CloseStatus status)
            throws Exception {
        sessions.remove(session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        log.info("收到websocket数据:{} ", payload);

        // 将 JSON 字符串转换为 Map
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> jsonMap = mapper.readValue(payload, new TypeReference<Map<String, Object>>() {
        });

        // 获取 type、topic 和 data
        String type = (String) jsonMap.get("type");
        String command = (String) jsonMap.get("command");
        String rtuCode = (String) jsonMap.get("rtuCode");
        String topic = "";
        String data = "";

        if("test-connection".equalsIgnoreCase(command)){
            topic = "$creq/"+rtuCode;
            data = "$"+rtuCode.toUpperCase()+"0001"+"FF\r\n";
        }

        // 使用 TestController 中的 mqttClient 发送 MQTT 消息
        MqttClient mqttClient = testController.getMqttClient();
        if (mqttClient != null && mqttClient.isConnected()) {
            try {
                MqttMessage mqttMessage = new MqttMessage(data.getBytes());
                mqttClient.publish(topic, mqttMessage);
                log.info("已发送 MQTT 消息到主题 {}: {}", topic, data);
            } catch (MqttException e) {
                log.error("发送 MQTT 消息时出错: {}", e.getMessage());
            }
        } else {
            log.error("MQTT 客户端未连接，无法发送消息");
        }
    }

    public static void sendMessageToAllClients(String message) {
        for (WebSocketSession session : sessions) {
            if (session.isOpen()) {
                try {
                    session.sendMessage(new TextMessage(message));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    }
